<?php
// +---------------------------------------------------------------------------------
// | ECODE [ 随心而行 勿忘始终]
// +---------------------------------------------------------------------------------
// | Copyright (c) 2017 ECODE All rights reserved.
// +---------------------------------------------------------------------------------
// | Author: 鬼谷子 <majianwei168@outlook.com>
// +---------------------------------------------------------------------------------
namespace app\admin\controller;

class Category extends Base
{
	public function index()
	{
		$data = array();
		$page = '';

		$data = model('Category')->lists();

		$formatData = $this->getcate($data ['list']);
		foreach($formatData as $k => $v){
			$formatData [$k]['title'] = str_repeat('&nbsp;&nbsp;&nbsp;',$v['level']).'|-'.$v['title'];
		}

		$this->assign('list', $formatData);
		$this->assign('page', $data ['page']);
		return view();
	}

	public function add($pid=0)
	{
		if($this->isPost()) {
			$post = input();
			$res = model('Category')->updates($post); //更新、添加、删除 回的变量 $res  查询回业的变量是 $data

			if($res < 0) {
				$this->error(model('Category')->getMessage($res));
			}
			$this->success('操作成功', url('index'));

		} else {

			$ptitle = model('Category')->where('id',$pid)->value('title');
			$ptitle = $ptitle == NULL ? '无' : $ptitle;
			$this->assign('ptitle', $ptitle);
			$this->assign('pid', $pid);
			return view('edit');
		}
	}

	public function edit($id)
	{
		if($this->isPost()) {
			$post = input();
			$res = model('Category')->updates($post, $post ['id']); //更新、添加、删除 回的变量 $res  查询回业的变量是 $data

			if($res < 0) {
				$this->error(model('Category')->getMessage($res));
			}
			$this->success('操作成功', url('index'));

		} else {

			$data = model('Category')->getone($id);
			$ptitle = model('Category')->where('id',$data ['pid'])->value('title');
			$ptitle = $ptitle == NULL ? '无' : $ptitle;
			$this->assign('ptitle', $ptitle);
			$this->assign('pid', $data ['pid']);
			$this->assign('data', $data);
			return view('edit');
		}

	}

	public function del($id)
	{
		$res = model('Category')->del($id);
		if($res == 1) {
			$this->success('操作成功', url('index'));
		} else {
			$this->error('操作失败');
		}
	}


	public function getcate($data,$pid = 0,$level=0)
	{
		$level++;
		$cateArr = array();
		//遍历数据
		foreach($data as $v){
			if($v['pid'] == $pid){			//把当前父id下的分类存到$cateArr中
				$v['level'] = $level;		//把深度(层数)一起存到$cateArr中
				$cateArr[] = $v;
				
				//查看这个分类 是否有 子分类  如果有继续加入到 $cateArr
				$cateArr = array_merge($cateArr,$this->getcate($data,$v['id'],$level));
			}
		}
		//返回当前的分类数据
		return $cateArr;
	}

}